package com.origon360.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SHA256CredentialManagerImpl implements CridentialManager {
	
	private static final String SHA2_ALGORITHM = "SHA-256";
	
	private static final String UUID_SEPARATOR = "-";
	
	private static final String EMPTY_STRING = "";
	
	private static Log log = LogFactory.getLog(SHA256CredentialManagerImpl.class);
	
	
	protected static MessageDigest getMessageDigest() throws IllegalStateException{
		try {
			return MessageDigest.getInstance(SHA2_ALGORITHM);
		} catch (NoSuchAlgorithmException e) {

			log.fatal("Credential Manager Failed to obtain SHA-2 Algorithm instance", e);
			throw new IllegalStateException("SHA-1 Algorithm instance unavailable", e);
		}
	}
	
	public static String encryptWithSalt(String plainTextPassword, String salt){
		
		byte[] rawSHA = null;
		byte[] base64SHA = null;
		
		MessageDigest md = getMessageDigest();
		md.update(CridentialUtils.getUTF8Bytes(salt));
		
		rawSHA = md.digest(CridentialUtils.getUTF8Bytes(plainTextPassword));
		
		base64SHA = Base64.encodeBase64(rawSHA);
		
		return CridentialUtils.getUTF8String(base64SHA);
		
	}
	
	public static String getSHA256EncryptionWithSalt(String plainTextPassword){
		 String salt = UUID.randomUUID().toString().replace(UUID_SEPARATOR, EMPTY_STRING);
		 
		 String saltedPassword = encryptWithSalt(plainTextPassword, salt);
		 
		 return salt + saltedPassword;
	}
	
	@Override
	public String encrypt(String plainText) {		
		return null;
	}

	@Override
	public String encrypt(String plainTextPassword, String salt) {
		return encryptWithSalt(plainTextPassword, salt) ;
	}

}
